class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def reverseList(head):
    if not head or not head.next: # 空链表或只有一个节点
        return head
    else:
        prev = None # 前一个节点
        curr = head # 当前节点
        while curr:
            next_temp = curr.next   # 保存下一个节点
            curr.next = prev        # 当前节点指向前一个节点（反转）
            prev = curr             # 前一个节点移动到当前节点
            curr = next_temp        # 当前节点移动到下一个节点
        return prev
# 工具函数：从列表构造链表
def build_linked_list(values):
    if not values: # 空列表
        return None
    head = ListNode(values[0]) # 头节点
    current = head
    for val in values[1:]:
        current.next = ListNode(val)
        current = current.next
    return head

# 工具函数：打印链表
def print_linked_list(head):
    result = []
    while head:
        result.append(head.val)
        head = head.next
    print(result)

# 示例运行
if __name__ == '__main__':
    head = build_linked_list([1, 2, 3, 4, 5])
    reversed_head = reverseList(head)
    print_linked_list(reversed_head)
